#!/usr/bin/env node

const https   = require('https'),
      url     = require('url'),
      fs=require('fs'),
      file='./content.txt',
      addr    = 'https://maoyan.com/films?showType=3',
      cheerio = require('cheerio');

let opt = url.parse(addr);

opt.headers = {
  'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3947.100 Safari/537.36'
    
};


https.get(opt, res=>{
  if(res==undefined) console.log('请求失败');
  let data='';
  let valueObj=[];
  let arr=[];
  res.on('data',(chunk)=>{
    data+=chunk;
  });

  res.on('end',()=>{
    let $=cheerio.load(data);
    let list=$('dd .movie-item-title a');
    let score=$('.movie-list dd .channel-detail-orange') ;  
    for(let i=0;i<list.length;i++){
      let text = $(list[i]).text();
      let movieId = $(list[i]).attr('data-val');
      var str=movieId.slice(9,movieId.length-1);
      valueObj[i]={
        'movieId':str,
        'movieName':text
      };

    }
    
    let j=0;
    for(let i=0;i<score.length;i++){
    
      if(score[i].name !=='span') {
        arr[j]=$(score[i]).text();
        j++;
        //console.log($(score[i]).text());
      }
    }
    console.log(arr);
    //循环arr，遍历到valueObj里面:
    for(let i=0;i<arr.length;i++){
      valueObj[i]['movieRange']=arr[i];
    }
    console.log(valueObj);
    //读取到一个文件里面去
    fs.writeFileSync(file,JSON.stringify(valueObj));
  });
});


